package com.fly.monitor.console.aspect;

import com.fly.monitor.core.enums.TraceKey;
import com.fly.monitor.core.helper.MDCHelper;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.MDC;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

@Aspect
@Component
public class SpanNodeAspect {

    @Pointcut("execution(* com.fly.monitor.console..*.*(..))")
    public void pointCut() {
    }

    @Around(value = "pointCut()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        String traceId = MDC.get(TraceKey.TRACE_ID.getKey());
        String spanId = MDC.get(TraceKey.SPAN_ID.getKey());
        String logicId = MDC.get(TraceKey.LOGIC_ID.getKey());
        if (!StringUtils.isEmpty(traceId) && !StringUtils.isEmpty(spanId) && !StringUtils.isEmpty(logicId)) {
            String newLogicId = MDCHelper.incrLogicId(logicId);
            MDC.put(TraceKey.LOGIC_ID.getKey(), newLogicId);
            MDC.put(TraceKey.SPAN_ID.getKey(), MDCHelper.getNewSpanId(spanId, logicId));
        }
        return point.proceed();
    }

}